package com.cll.learn.rpc.common.coder;

import com.cll.learn.rpc.common.dto.RpcResponse;
import com.cll.learn.rpc.common.serializer.Serializable;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 描述信息:
 * 对RpcResponse对象进行编码
 * @author CLL
 * @version 1.0
 * @date 2020/9/14 15:31
 */
@RequiredArgsConstructor
public class RpcResponseEncoder extends MessageToByteEncoder<RpcResponse> {

    private static final Logger logger = LoggerFactory.getLogger(RpcResponseEncoder.class);

    @NonNull
    private Class<?> clazz;

    @NonNull
    private Serializable serializable;

    @Override
    protected void encode(ChannelHandlerContext ctx, RpcResponse msg, ByteBuf out) throws Exception {
        logger.info("===>>> encode rpcResponse object");
        if (null != this.clazz && this.clazz.isInstance(msg)) {
            byte[] byteData = this.serializable.serializable(msg);
            out.writeInt(byteData.length);
            out.writeBytes(byteData);
        } else {
            logger.error("****** 接收到的进行编码的对象不是传递过来的类型的实例");
        }
    }
}